<template>
	<div class="page-wrapper">
		<el-scrollbar height="100%">
			<div>
				<el-select v-model="proid" filterable placeholder="请先选择产品" style="width: 230px;" @change="selectChange">
                    <el-option
                    v-for="item in prolist"
                    :key="item.id"
                    :label="item.label"
                    :value="item.value"
                    />
                </el-select>
			</div>
            <div class="bold textC font20" v-if="proid">{{totalname}}库存剩余：{{ totalnum }}</div>
			<div v-loading="loading">
				<div ref="mainRef" style="width: 100%; height: 700px"></div>
			</div>
		</el-scrollbar>
        <el-dialog v-model="visible" :title="title" width="1200px" center :destroy-on-close="true">
           <div class="w100">
            <!-- <div class="textR mb10">{{ totalText }}</div> -->
            <div class="flex mb10 flexL">
                <div v-if="itemType==1">入库时间：</div>
                <div v-if="itemType==2">出库时间：</div>
                <div class="mr10">
                    <el-date-picker :shortcuts="SHORTCUTS" v-model="record_time" style="width:240px;" @change="dataChange" type="daterange" range-separator="-" start-placeholder="开始时间" end-placeholder="结束时间" value-format="YYYY-MM-DD" clearable />
                </div>
                <div class="mr10" v-if="itemType==2">
                    <el-select v-model="search.customer_name" placeholder="选择客户" clearable style="width: 100%;">
                        <el-option v-for="i in customerList" :key="i.value" :label="i.label" :value="i.label" />
                    </el-select>
                </div>
                <div class="mr10" v-if="itemType==2">
                    <el-select v-model="search.department_name" placeholder="选择部门" clearable style="width: 100%;">
                        <el-option v-for="i in departmentList" :key="i.value" :label="i.label" :value="i.label" />
                    </el-select>
                </div>
                <div class="mr10" v-if="itemType==1">
                    <el-select v-model="search.supplier_name" placeholder="选择供应商" clearable style="width: 100%;">
                        <el-option v-for="i in supplierList" :key="i.value" :label="i.label" :value="i.value" />
                    </el-select>
                </div>
                <div class="mr10">
                    <el-input v-model="search.batch_no" placeholder="输入批次号搜索" clearable style="width: 180px;"></el-input>
                </div>
                <div>
                    <el-button type="primary" @click="searchHandle()">搜索</el-button>
                </div>
            </div>
            <div class="mb10">
                表格当前页数据出入库数量汇总(不含分页)：<span class="bold">{{ totalNumPro }}</span>
            </div>
            <el-scrollbar height="600px">
                <el-table :data="itemList" border style="width: 100%" width="100%" height="100%" v-if="itemType==1">
                    <el-table-column prop="order_sn" label="入库单号" header-align="center" align="center"></el-table-column>
                    <el-table-column prop="in_time" label="入库时间" header-align="center" align="center" width="100"></el-table-column>
                    <el-table-column prop="in_type" label="入库类型" header-align="center" align="center">
                        <template #default="scope">
                            <span v-if="scope.row.in_type == 1">产品采购入库</span>
                            <span v-if="scope.row.in_type == 2">材料采购入库</span>
                            <span v-if="scope.row.in_type == 3">退货入库</span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="batch_no" label="批次号" header-align="center" align="center"></el-table-column>
                    <el-table-column prop="quantity" label="入库数量" header-align="center" align="center"></el-table-column>
                    <el-table-column prop="isused" label="已出库数量" header-align="center" align="center"></el-table-column>
                    <el-table-column prop="supplier_name" label="供应商名称" header-align="center" align="center"></el-table-column>
                    <el-table-column prop="operator" label="操作人" header-align="center" align="center"></el-table-column>
                    <el-table-column prop="created_at" label="操作时间" header-align="center" align="center" width="100"></el-table-column>
                </el-table>
                <el-table :data="itemList" border style="width: 100%" width="100%" height="100%" v-if="itemType==2">
                    <el-table-column prop="order_sn" label="出库单号" header-align="center" align="center"></el-table-column>
                    <el-table-column prop="out_time" label="出库时间" header-align="center" align="center" width="100"></el-table-column>
                    <el-table-column prop="out_type" label="出库类型" header-align="center" align="center">
                        <template #default="scope">
                            <span v-if="scope.row.out_type == 1">生产出库</span>
                            <span v-if="scope.row.out_type == 2">销售出库</span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="batch_no" label="批次号" header-align="center" align="center"></el-table-column>
                    <el-table-column prop="quantity" label="出库数量" header-align="center" align="center"></el-table-column>
                    <el-table-column prop="customer_name" label="客户名称" header-align="center" align="center"></el-table-column>
                    <el-table-column prop="department_name" label="部门名称" header-align="center" align="center" show-overflow-tooltip></el-table-column>
                    <el-table-column prop="remark" label="出库备注" header-align="center" align="center"></el-table-column>
                    <el-table-column prop="operator" label="操作人" header-align="center" align="center"></el-table-column>
                    <el-table-column prop="created_at" label="操作时间" header-align="center" align="center" width="100"></el-table-column>
                </el-table>
            </el-scrollbar>
           </div>
        </el-dialog>
	</div>
</template>

<script setup lang="ts">
import { onMounted, ref, computed, onBeforeUnmount } from 'vue'
import { getCustomerList, getInventoryItem, getProduct, getProductListAll, getSupplierList } from '@/api/api'
import { ElMessage } from 'element-plus'
import { Sort } from '@element-plus/icons-vue'
import { hasRule } from '@/utils/tool'
import { SHORTCUTS } from '@/config'
import * as echarts from 'echarts'
import { departmentwithuser } from '@/api/org'

const proid = ref('');
const prolist = ref([]);
const totalText = ref('');
const totalname = ref('');
const totalnum = ref(0);
const title = ref('');
const itemType = ref(1);
const visible = ref(false);
const itemList = ref([]);
const currentMenu = ref()
const activeName = ref('tab1')
const loading = ref(false)
const search = ref({
    id: '',
    name: '',
    attr_name_fill: '',
    attr_name: '',
    start: '',
    end: '',
    customer_name: '',
    supplier_name: '',
    batch_no: '',
    department_name: '',
})
const totalNumPro = ref(0);
const customerList = ref([])
const departmentList = ref([])
const supplierList = ref([])
const record_time = ref([])
onBeforeUnmount(() => {
    if (currentMenu.value && currentMenu.value.parentNode === document.body) {
        document.body.removeChild(currentMenu.value) // 清除之前的菜单元素
    }
})
onMounted(() => {
    getAll();
	init('心型染发夹',2)
    getSupplierList({page:1,per_page:9999}).then((result) => {
        // console.log(result.data.data);
        supplierList.value = result.data.data.map((item) => {
            return {
                ...item,
                label: item.name,
                value: item.name,
            }
        })
    }).catch((err) => {
        
    });
    getCustomerList({page:1,per_page:9999}).then((result) => {
        // console.log(result.data.data);
        customerList.value = result.data.data.map((item) => {
            return {
                ...item,
                label: item.name,
                value: item.name,
            }
        })
    }).catch((err) => {
        
    });
    departmentwithuser({}).then((result) => {
        console.log(result.data);
        departmentList.value = result.data.map((item) => {
            return {
                ...item,
                label: item.department_name,
                value: item.department_name,
            }
        })
    }).catch((err) => {
        
    });
})
// 选择时间范围
const dataChange = (e: any) => {
	if(e){
		search.value.start = e[0] + ' 00:00:00'
		search.value.end = e[1] + ' 23:59:59'
	}else{
		search.value.start = ''
		search.value.end = ''
	}
}
const getAll = () => {
    getProductListAll().then((result) => {
        const list = result.data.map(item => {
            return {
                id: item.id,
                value: item.id,
                label: item.name
            }
        })
        prolist.value = list;
        proid.value = 2;
    }).catch((err) => {
        
    });
}
const selectChange = (e) => {
    console.log(e);
    if(e){
        const proitem = prolist.value.find(i => i.id == e)
        init(proitem.label,proitem.id)
    }
}
const getFontColor = text => {
	const colorList = [
		{ font: '红', color: '#C23019' },
		{ font: '白', color: '#EDEDED' },
		{ font: '蓝', color: '#2C3D95' },
		{ font: '黑', color: '#303030' },
		{ font: '黄', color: '#EDCA50' },
		{ font: '绿', color: '#127A00' },
		{ font: '咖', color: '#4C1B01' },
		{ font: '浅蓝', color: '#79A2D3' },
		{ font: '橙', color: '#D86E13' },
		{ font: '紫', color: '#983593' }
	]
	const item = colorList.find(i => i.font == text)
	if (item) {
		return item.color
	} else {
		return '#303030'
	}
}
const mainRef = ref()
const myChart = ref(null)
const init = async (name, one) => {
    totalname.value = name;
    let rotate = 0;
    totalnum.value = 0;
	loading.value = true
	if (myChart.value === null) {
		myChart.value = echarts.init(mainRef.value)
	}
	let data1 = await getProduct(one)
	let sku1 = null
	sku1 = data1.data.sku;
	let xData = []
	let seriesData = [
		{
			label: {
				show: true,
				position: 'top', // 顶部显示
				formatter: params => {
					return params.value
				} // 显示数据值
			},
			data: [],
			type: 'bar',
            barMaxWidth: '80',
			stack: 'stack1' // 使用相同的堆叠名，以便在同一根柱子上绘制
		}
	]
	sku1.forEach(item => {
        totalnum.value += item.inventory;
        xData.push(`${item.attr?.two_name?item.attr.two_name+'-':''}${item.attr_name}`)
        seriesData[0].data.push({ diyname: name, diyid:item.id, value: item.inventory, itemStyle: { color: '#409EFF' }, emphasis: { disabled: true } })
    })
    if(sku1.length > 10) {
        rotate = 30
    }
    if(sku1.length > 30) {
        rotate = 40
    }
    if(sku1.length > 40) {
        rotate = 50
    }
    if(sku1.length > 50) {
        rotate = 60
    }
	// console.log(seriesData)
	let option = {
		animation: false,
		xAxis: {
			type: 'category',
			data: xData,
            axisLabel: {
                show: true,
                rotate: rotate,//35度角倾斜显示
            }
		},
		yAxis: {
			type: 'value'
		},
		series: seriesData,
	}
	// 绘制图表
	myChart.value.setOption(option)
    chartLeftEvent(myChart.value);
    chartRightEvent(myChart.value);
	loading.value = false
}
const chartRightEvent = (chart) => {
    chart.getZr().on('contextmenu', params => {
		params.event.preventDefault() // 取消默认右击事件
		// 使用箭头函数
		if (currentMenu.value && currentMenu.value.parentNode === document.body) {
			document.body.removeChild(currentMenu.value) // 清除之前的菜单元素
		}
	})
}
const chartLeftEvent = (chart) => {
    chart.on('click', params => {
        const proitem = prolist.value.find(i => i.id == proid.value);
        const name = proitem.label;
		// console.log('params', params)
        if(!hasRule('admin/inventory/inventory')){
            return;
        }
		if (currentMenu.value && currentMenu.value.parentNode === document.body) {
			document.body.removeChild(currentMenu.value) // 清除之前的菜单元素
		}

		const menu = document.createElement('div')
		menu.classList.add('custom-menu') // 添加自定义样式类名
		menu.style.cssText = `
            left: ${params.event.event.pageX}px;
            top: ${params.event.event.pageY}px;
        `
		document.body.appendChild(menu)

		const menuItem1 = document.createElement('div')
		menuItem1.className = 'menu-item'
		menuItem1.style.cssText = `
          border-radius: 0px 10px 0px 0px;
        `
		menuItem1.innerText = '查看入库记录'
		menuItem1.onclick = () => {
			// console.log('查看入库记录')
            handleCheck(name, params,1,true);
			if (currentMenu.value && currentMenu.value.parentNode === document.body) {
				document.body.removeChild(currentMenu.value) // 清除之前的菜单元素
			}
		}
		menu.appendChild(menuItem1)

		const menuItem2 = document.createElement('div')
		menuItem2.className = 'menu-item'
		menuItem2.style.cssText = `
          border-radius: 0px 0px 0px 10px;
        `
		menuItem2.innerText = '查看出库记录'
		menuItem2.onclick = () => {
			// console.log('查看出库记录')
            handleCheck(name, params,2,true);
			if (currentMenu.value && currentMenu.value.parentNode === document.body) {
				document.body.removeChild(currentMenu.value) // 清除之前的菜单元素
			}
		}
		menu.appendChild(menuItem2)

		currentMenu.value = menu // 保存当前菜单元素
	})
}
const searchHandle = () => {
    handleCheck(search.value.name,{
        name: search.value.attr_name,
        data: {
            diyid: search.value.id,
        }
    },itemType.value);
}
const handleCheck = (name, row, type,first) => {
    if(first === true){
        record_time.value = [];
        search.value.start = '';
        search.value.end = '';
        search.value.customer_name = '';
        search.value.supplier_name = '';
        search.value.batch_no = '';
        search.value.department_name = '';
    }
    const params = {
        product_id: row.data.diyid,
        type: type,
    }
    totalNumPro.value = 0;
    search.value.id = row.data.diyid;
    search.value.name = name;
    search.value.attr_name = row.name;
    itemType.value = type;
    if(type==1){
        title.value = `${name}（${row.name}）入库记录`;
        if(search.value.supplier_name){
            params.supplier_name = search.value.supplier_name;
        }
        if(search.value.customer_name){
            params.customer_name = search.value.customer_name;
        }
        if(search.value.department_name){
            params.department_name = search.value.department_name;
        }
    }else{
        title.value = `${name}（${row.name}）出库记录`;
        if(search.value.supplier_name){
            params.supplier_name = search.value.supplier_name;
        }
        if(search.value.customer_name){
            params.customer_name = search.value.customer_name;
        }
        if(search.value.department_name){
            params.department_name = search.value.department_name;
        }
    }
    if(search.value.start&&search.value.end){
        params.start = search.value.start;
        params.end = search.value.end;
    }
    if(search.value.batch_no){
        params.batch_no = search.value.batch_no;
    }
    itemList.value = [];
    visible.value = true;
    totalText.value = '';
    getInventoryItem(params).then((result) => {
        itemList.value = result.data;
        const tal = result.data.reduce((total, item) => {
            return total + item.quantity;
        }, 0)
        if(type==1){
            totalText.value = `入库总数量：${Math.floor(tal)}`;
        }else{
            totalText.value = `出库总数量：${Math.floor(tal)}`;
        }
        const ttttal = itemList.value.reduce((total,item)=>total+item.quantity, 0);
        totalNumPro.value = Math.ceil(ttttal);
    }).catch((err) => {
        
    });
}
</script>
<style>
/* echarts图表样式 */
.custom-menu {
	position: absolute;
	width: 130px;
	box-shadow: rgb(0 0 0 / 30%) 1px 1px 3px;
	z-index: 999;
	background: rgb(69 140 199 / 80%);
	border: none;
	border-radius: 0px 10px 0px 10px;
	color: #fff;
	display: flex;
	flex-direction: column;
	align-items: center;
}

.menu-item {
	padding: 5px 0px;
	cursor: pointer;
	width: 100%;
	display: flex;
	justify-content: center;
}

.menu-itemborder1 {
	border-radius: 0px 10px 0px 0px;
}

.menu-itemborder2 {
	border-radius: 0px 0px 0px 10px;
}

.menu-item:hover {
	background-color: #a2bbda;
}
</style>
